

import { SYNC_UPDATA }  from "./const"

 
export default{
    //数据更新
    initCar( {commit} ){
        console.log('succ data inited')
        let cars = getCars();
        commit( SYNC_UPDATA ,cars )
    },




    //添加购物车
    addCar( {commit} ,goods){
        // console.log( goods )
        // console.log( goods.id )

        setTimeout ( ()=>{
            let cars = getCars();

            let isHas = cars.some( item => {
                if( item.id === goods.id ){
                    item.num ++ 
                    return true
                }
            })

            if( !isHas ){
                goods.num = 1
                cars.push( goods )
            }
            
            localStorage.cars = JSON.stringify( cars )
            commit( SYNC_UPDATA ,cars )
        },500)

         
    },
    //减少
    reduceCar( {commit} , good){
        
        setTimeout( () =>{

            let cars = getCars();

            cars = cars.filter((item) => {
                if( item.id === good.id){
                    item.num--
                    if( item.num< 0){
                        return false
                    }
                    return true
                }
                return true
            })       

            localStorage.cars = JSON.stringify( cars )
            commit( SYNC_UPDATA, cars)

        },300)
       
    },

    checkLogin:({commit},payload)=>{
            commit('checkLogin',playload)
    }
}  


function getCars(){
    return JSON.parse( localStorage.cars? localStorage.cars : '[]')
}